package com.shujia.share;


/*
三种创建线程的方式都可以使用资源的共享
Runnbale方法更加容易
继承Thread类怎么实现资源共享???
 */
public class ShareDemo implements Runnable {
    // 共享
    private NumberCount numberCount;

    // 不共享
    private Person person;

    public ShareDemo(NumberCount numberCount, Person person) {
        this.numberCount = numberCount;
        this.person = person;
    }

    public static void main(String[] args) throws Exception {
        NumberCount numberCount = new NumberCount();

        Person p1 = new Person();
        p1.age = 30;
        Person p2 = new Person();
        p2.age = 40;

        ShareDemo demo = new ShareDemo(numberCount, p1);
        ShareDemo demo1 = new ShareDemo(numberCount, p2);

        // new 不共享的资源,


        // 使用同一个Runnable实现类创建多个线程
        // 那么这个 ShareDemo 对象它在多个线程里面就是共享资源
        // Thread 类不是我们自定义, 所以无法添加属性
        Thread t1 = new Thread(demo);
        Thread t2 = new Thread(demo1);
        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(numberCount.getCount());
        System.out.println(p1.age);
        System.out.println(p2.age);


    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            numberCount.incr();
            person.age++;
        }
    }
}
